<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>
      <!-- 双向绑定数据 动态绑定规则 -->
      <el-form :model='ruleForm' :rules='rules' ref="loginFrom" autocomplete="off">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="输入用户名" v-model="ruleForm.username" ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="输入用户密码" v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item class="tc">
          <el-button type="primary" @click="onLogin">登 录</el-button>
          <!-- 重置 -->
          <el-button @click="$refs.loginFrom.resetFields()">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
// 需求：实现登录提交校验//1.给el-form表单绑定ref属性//2。给按钮绑定点击事件//3。通过ref获取表单组组件实例对象//4。调用validate方法
export default {
  name: 'login-page',
  data () {
    return {
      // 定义表单双向绑定的数据
      ruleForm: {
        username: '',
        password: ''
      },
      // 定义校验规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { pattern: /^\w{5,11}/, message: '长度在 5 到 11 个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    ...mapActions('user', ['loginAction']),
    async onLogin () {
      //  Promise语法糖的写法
      await this.$refs.loginFrom.validate()
      // console.log('校验通过')
      this.loginAction(this.ruleForm)

      // Promise写法
      // this.$refs.loginFrom.validate()
      //   .then(() => {
      //     console.log('校验通过')
      //   }).catch(() => {
      //     console.log('校验不通过')
      //   })
      // 回调函数的写法
      // this.$refs.loginFrom.validate((key) => {
      //   console.log(key)
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: center;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header{
      height: 80px;
      line-height: 40px;
      background: rgba(114,124,245,1);
      text-align: center;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
